package com.mrd.gtimp.business.service;

import com.mrd.base.BaseBiz;
import com.mrd.gtimp.business.entity.BusinessKey;
import com.mrd.spring.repository.BaseRepository;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

/**
 * Created by lenovo on 2017/6/27.
 */
@Service
public class BusinessKeyBiz extends BaseBiz<BusinessKey> {

  @Override
  @Resource
  @Qualifier("businessKeyDao")
  public void setBaseRepository(BaseRepository<BusinessKey, String> baseRepository) {
    this.baseRepository = baseRepository;
  }


  public String newBusinessKey() throws Exception {
    BusinessKey businessKey = this.getBusinessKey();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    int count = businessKey.getBusinessCount();
    boolean isNewDate = false;
    Date businessDate = businessKey.getBusinessDate();
    if (!sdf.format(businessKey.getBusinessDate()).equalsIgnoreCase(sdf.format(new Date()))) {
      count = 1;
      businessDate = new Date();
      isNewDate = true;
    }

    String businessIdVal;

    String businessPostfixExpression = businessKey.getBusinessPostfixExpression();
    if (StringUtils.isNotEmpty(businessPostfixExpression)) {
      DecimalFormat decimalFormat = new DecimalFormat(businessPostfixExpression);
      businessIdVal =
          businessKey.getBusinessPrefix() + sdf.format(businessDate) + decimalFormat.format(count);
    } else {
      businessIdVal = String
          .format(businessKey.getBusinessPrefix() + sdf.format(businessDate) + "%04d", count);
    }

    int result = this.updateBusinessKey(businessKey, isNewDate);
    if (result == 0) {
      return this.newBusinessKey();
    }
    return businessIdVal;

  }

  private BusinessKey getBusinessKey() throws Exception {
    List<BusinessKey> list = this.findAllEntity();
    if (CollectionUtils.isEmpty(list) || list.get(0) == null) {
      throw new Exception("生成业务编号错误！");
    }
    return list.get(0);
  }


  private int updateBusinessKey(BusinessKey businessKey, Boolean isNewDate) throws Exception {
    int count = businessKey.getBusinessCount();
    if (isNewDate) {
      count = 1;
    }
    String
        sql =
        "update t_biz_business_key t set t.BUSINESS_DATE=sysdate,t.BUSINESS_COUNT='" + (count + 1)
        + "',t.BUSINESS_VERSION='" + (businessKey.getBusinessVersion() + 1)
        + "' where t.BUSINESS_VERSION='" + businessKey.getBusinessVersion() + "'";
    return this.baseRepository.updateBySql(sql);
  }
}
